package main

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"fmt"
)

func main() {
	str := []byte("花落知多少,谁知天上宫阙，今夕是何年呀") //原始数据
	key := []byte("yqIPMTyxhCUvLrAHSvhuyEcTByPwAdAh")            //密钥 为16位
	mi_str := aes_ctr_encryption(str, key)
	fmt.Println("加密成功：", string(mi_str))
	jie_str := aes_ctr_decrypt(str, key)
	fmt.Println("解密成功：", string(jie_str))
}

func aes_ctr_encryption(str []byte, key []byte) []byte {
	fmt.Println("加密前key长度：",len(key))
	// 1创建接口
	block, err := aes.NewCipher(key)
	if err != nil {
		panic(err)
	}
	// 2分组
	fmt.Println("加密后key分组长度为：",block.BlockSize())
	iv := bytes.Repeat([]byte("1"), block.BlockSize())
	stream := cipher.NewCTR(block, iv)

	// 3加密
	stream.XORKeyStream(str, str)
	return str
}
//解密
func aes_ctr_decrypt(str []byte, key []byte) []byte {
	fmt.Println("解密前key长度：",len(key))
	// 1创建接口
	block, err := aes.NewCipher(key)
	if err != nil {
		panic(err)
	}
	// 2分组
	fmt.Println("解密后key分组长度为：",block.BlockSize())
	iv := bytes.Repeat([]byte("1"), block.BlockSize())
	stream := cipher.NewCTR(block, iv)

	// 3加密
	stream.XORKeyStream(str, str)
	return str
}
